import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Quickstart {

    //使用的日志文件
    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);

    public static void main(String[] args) {
        //【死代码】----------------------------------------------------------------
        //创建一个用户权限管理者
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //可以通过工厂创建安全管理器
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        //【核心代码】---------------------------------------------------------------------
        //获取当前的用户对象
        Subject currentUser = SecurityUtils.getSubject();
        //通过当前用户拿到session
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");//存值
        String value = (String) session.getAttribute("someKey");//取值
        if (value.equals("aValue")) { //判断
            log.info("从session中获得了someKy的值=" + value + "");
        }
        //判断当前用户是否被认证
        if (!currentUser.isAuthenticated()) {
            //通过账号密码生成令牌
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);//记住我
            try {
                currentUser.login(token);//登录
            } catch (UnknownAccountException uae) {
                log.info("[登录失败]:用户不存在:" + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("[登录失败]:密码错误:" + token.getPrincipal());
            } catch (LockedAccountException lae) {
                //可以使用shiro实现:多次登录密码错误,然后锁定用户
                log.info("[登录失败]:当前账号: " + token.getPrincipal() + "已经被锁定了!");
            }
            catch (AuthenticationException ae) {
                //上面所有的异常类都是AuthenticationException的子类
                log.info("[登录失败]:服务器异常");
            }
        }

        log.info("用户登录成功!当前用户认证信息:[" + currentUser.getPrincipal() + "]");

        //判断是否拥有角色
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }
        //粗粒度(进行一个简单的权限验证)
        if (currentUser.isPermitted("lightsaber:wield")) { //在配置文件中配置过
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }
        //细粒度(更加严格的权限验证)
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        //当前用户退出登录(注销)
        currentUser.logout();
        //java程序结束
        System.exit(0);
    }
}
